package com.mf.morefun.ui.grindingears;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.adapter.GrindingEarsAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.DeleteEarsBean;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.GrindingEarsBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.ReadDetailTypeListener;
import com.mf.morefun.requestbean.RequestDeleteOneEars;
import com.mf.morefun.requestbean.RequestEarsBean;
import com.mf.morefun.service.MusicPositionService;
import com.mf.morefun.service.MusicService;
import com.mf.morefun.ui.HomePagerActivity;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.ui.gifts.GiftsListActivity;
import com.mf.morefun.ui.moreread.DoTestActivity;
import com.mf.morefun.ui.moreread.MoreReadingActivity;
import com.mf.morefun.ui.person.MineInfoActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.mf.morefun.widget.TransformationEarsUtils;
import com.mf.morefun.widget.TransformationHomeUtils;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.RotateAnimation;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.support.constraint.Constraints.TAG;

public class GrindingEarsActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_type)
    ImageView ivType;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.iv_before)
    ImageView ivBefore;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.iv_next)
    ImageView ivNext;
    @BindView(R.id.songProgress)
    TextView songProgress;
    @BindView(R.id.seekbar_music)
    SeekBar seekbarMusic;
    @BindView(R.id.songDuration)
    TextView songDuration;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.ll_add)
    LinearLayout llAdd;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.lv_song)
    ListView lvSong;
    private SPUtils mSPutils;
    private List<GrindingEarsBean> mGrindingEarsList = new ArrayList<>();
    private GrindingEarsAdapter adapter;
    private int selectIndex = 0;
    private int currentType = 0;
    private MusicService mMusicService = null;
    private RoundProcessDialog dialog;
    private RotateAnimation animationSmall;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private boolean isBind = false;//是否已经绑定过播放服务
    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isBind = true;
            if (null != mGrindingEarsList && mGrindingEarsList.size() > 0) {
                mMusicService = ((MusicService.MyBinder) service).getService(mGrindingEarsList, GrindingEarsActivity.this);
                mMusicService.songNum = selectIndex;
                mMusicService.play();
                if (null != dialog && !dialog.isShow()) {
                    dialog.setMessage("加载歌曲中...");
                    dialog.show();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            mMusicService = null;
        }
    };

    private void bindServiceConnection() {
        Intent intent = new Intent(GrindingEarsActivity.this, MusicService.class);
        startService(intent);
        bindService(intent, sc, this.BIND_AUTO_CREATE);
    }

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_gringdingears;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSPutils = new SPUtils(getApplicationContext());
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPutils.getString(Configuration.USERPHONE), mSPutils.getString(Configuration.USERPASSWORD));
        }
        EventBus.getDefault().register(this);
        dialog = new RoundProcessDialog(GrindingEarsActivity.this, "搜素歌曲中...");
        songProgress.setText("00:00");
        songDuration.setText("00:00");
        mMusicService = new MusicService();
        adapter = new GrindingEarsAdapter(GrindingEarsActivity.this, mGrindingEarsList);
        adapter.setListener(new ReadDetailTypeListener() {//删除一个
            @Override
            public void callBack(int position) {
                BackIdeaPop pops = new BackIdeaPop(GrindingEarsActivity.this);
                pops.showPop("确定要删除 " + mGrindingEarsList.get(position).getName() + "吗?", 2, position);
            }
        });
        adapter.setSelectIndex(selectIndex);
        lvSong.setAdapter(adapter);
        lvSong.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //选中播放哪个
                songProgress.setText("00:00");
                songDuration.setText("00:00");
                selectIndex = position;
                if (null != adapter) {
                    adapter.setSelectIndex(selectIndex);
                    lvSong.setSelection(selectIndex);
                    adapter.notifyDataSetInvalidated();
                }
                tvTitle.setText(mGrindingEarsList.get(selectIndex).getName());
                startPlay();
                showCicleImg();
                reStartAnimation();
            }
        });
        animationSmall = new RotateAnimation();
        animationSmall.with(ivBg);
        animationSmall.start();
        initGetSongList();
        initSeekBar();
        MoreFunApplication.isOut = false;//这里是进入
        Intent intent = new Intent();
        intent.setAction("GETMUSICPOSITION");
        intent.setPackage("com.mf.morefun"); //指定启动的是那个应用（lq.cn.twoapp）中的Action(b.aidl.DownLoadService)指向的服务组件
        startService(intent);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("DELETE");
        registerReceiver(mReceiver, mFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("DELETE")) {
                //删除哪个
                initDeleteEars(intent.getIntExtra("POSITION", 0));
            }
        }
    };

    private void initSeekBar() {
        seekbarMusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (null != mMusicService && fromUser) {
                    mMusicService.pause();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (songDuration.getText().toString().equals("00:00")) {
                    seekBar.setProgress(0);
                } else {
                    int progress = seekBar.getProgress();
                    int seekBarMax = seekBar.getMax();
                    if (null != mMusicService) {
                        mMusicService.player
                                .seekTo((int) ((((double) duation) * ((double) progress)) / ((double) seekBarMax)));//跳到该曲该秒
                        mMusicService.goPlay();
                    }
                }
            }
        });
    }

    private void initDeleteEars(int position) {
        if (null != dialog && !dialog.isShow()) {
            dialog.setMessage("正在删除...");
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.DELETEONEEARS);
        RequestDeleteOneEars requestDeleteOneEars = new RequestDeleteOneEars();
        RequestDeleteOneEars.UserBean userBean = new RequestDeleteOneEars.UserBean();
        userBean.setId(mSPutils.getString(Configuration.USERID));
        requestDeleteOneEars.setId(mGrindingEarsList.get(position).getId());
        requestDeleteOneEars.setUser(userBean);
        params.setBodyContent(JSON.toJSONString(requestDeleteOneEars));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                if (!StringUtils.isEmpty(result)) {
                    DeleteEarsBean deleteEarsBean = JSON.parseObject(result, DeleteEarsBean.class);
                    if (deleteEarsBean.getErrorCode() == 0) {
                        if (null == mGrindingEarsList || mGrindingEarsList.size() == 0){
                            return;
                        }
                        mGrindingEarsList.remove(position);
                        if (null != mGrindingEarsList && mGrindingEarsList.size() > 0){
                            if (selectIndex > (mGrindingEarsList.size() - 1)) {
                                selectIndex = mGrindingEarsList.size() - 1;
                            }
                            if (null != adapter) {
                                adapter.setSelectIndex(selectIndex);
                                lvSong.setSelection(selectIndex);
                                adapter.notifyDataSetInvalidated();
                            }
                            if (null != mMusicService && isBind){
                                mMusicService.setMusicList(mGrindingEarsList);
                                tvTitle.setText(mGrindingEarsList.get(selectIndex).getName());
                                startPlay();
                                showCicleImg();
                            }else {
                                bindServiceConnection();
                            }
                        }else {
                            if (null != adapter) {
                                adapter.notifyDataSetChanged();
                            }
                            if (null != mMusicService && null != mMusicService.player) {
                                mMusicService.stop();
                            }
                            seekbarMusic.setProgress(0);
                            songProgress.setText("00:00");
                            songDuration.setText("00:00");
                            tvTitle.setText("");
                            ivBg.setImageResource(R.mipmap.med_jiaopian);
                            ivPlay.setImageResource(R.mipmap.playing);
                            if (null != animationSmall) {
                                if (animationSmall.isShow()) {
                                    animationSmall.stop();
                                }
                            }
                            ivBg.clearAnimation();
                            selectIndex = 0;
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), deleteEarsBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(102);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void showCicleImg() {
        CircleCrop circleCrop = new CircleCrop();
        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
        Glide.with(GrindingEarsActivity.this).asBitmap().load(mGrindingEarsList.get(selectIndex).getCover()).listener(new mRequestListener(ivBg)).apply(options).into(new TransformationEarsUtils(ivBg, GrindingEarsActivity.this));
    }

    private class mRequestListener implements RequestListener {
        private ImageView ivPersonhead;

        public mRequestListener(ImageView ivPersonhead) {
            this.ivPersonhead = ivPersonhead;
        }

        @Override
        public boolean onLoadFailed(@org.jetbrains.annotations.Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            Log.d(TAG, "onException: " + e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
            Message msg = new Message();
            msg.what = 100;
            msg.obj = ivPersonhead;
            mHandler.sendMessage(msg);
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG, "model:" + model + " isFirstResource: " + isFirstResource);
            return false;
        }
    }

    ;

    private void initGetSongList() {
        if (null != dialog && !dialog.isShow()) {
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GRINDINGEARSLIST);
        RequestEarsBean requestEarsBean = new RequestEarsBean();
        requestEarsBean.setUserId(mSPutils.getString(Configuration.USERID));
        params.setBodyContent(JSON.toJSONString(requestEarsBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mGrindingEarsList.clear();
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<GrindingEarsBean> grindingEarsBeanList = JSON.parseArray(resultBean.getResult(), GrindingEarsBean.class);
                            mGrindingEarsList.addAll(grindingEarsBeanList);
                            if (null != mMusicService && isBind){
                                mMusicService.setMusicList(mGrindingEarsList);
                                startPlay();
                            }else {
                                bindServiceConnection();
                            }
                            tvTitle.setText(mGrindingEarsList.get(selectIndex).getName());
                            showCicleImg();
                        } else {
                            ToastUtils.show(getApplicationContext(), "暂无歌曲", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
                if (null != adapter) {
                    adapter.setSelectIndex(selectIndex);
                    lvSong.setSelection(selectIndex);
                    adapter.notifyDataSetInvalidated();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(102);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private int duation = 0;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x101://更新进度
                    if (null != mMusicService && null != mMusicService.player) {
                        songDuration.setText(formatTime(mMusicService.player.getDuration()));
                        songProgress.setText(formatTime(mMusicService.player.getCurrentPosition()));
                        double currentPosition = mMusicService.player.getCurrentPosition();
                        double duration = mMusicService.player.getDuration();
                        seekbarMusic.setProgress((int) ((currentPosition / duration) * 100));
                    }
                    break;
                case 100:
                    CircleCrop circleCrop = new CircleCrop();
                    RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                    Glide.with(GrindingEarsActivity.this).asBitmap().load(R.mipmap.med_jiaopian).apply(options).into(new TransformationEarsUtils((ImageView) msg.obj, GrindingEarsActivity.this));
                    break;
                case 102:
                    NetErrorPop errorPop = new NetErrorPop(GrindingEarsActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }

    //处理下一首 // 0是 顺序播放 1是随机播放 2是循环播放 3是单曲播放
    private void caluateNextIndex() {
        if (currentType == 0) {
            if (selectIndex == (mGrindingEarsList.size() - 1)) {
                selectIndex = selectIndex;
            } else {
                selectIndex++;
            }
        } else if (currentType == 1) {
            randomPlay();
        } else if (currentType == 2) {
            if (selectIndex == (mGrindingEarsList.size() - 1)) {
                selectIndex = 0;
            } else {
                selectIndex++;
            }
        } else {
            selectIndex = selectIndex;
        }
    }

    //处理上一首 // 0是 顺序播放 1是随机播放 2是循环播放 3是单曲播放
    private void caluateAfterIndex() {
        if (currentType == 0) {
            if (selectIndex == 0) {
                selectIndex = selectIndex;
            } else {
                selectIndex--;
            }
        } else if (currentType == 1) {
            randomPlay();
        } else if (currentType == 2) {
            if (selectIndex == 0) {
                selectIndex = (mGrindingEarsList.size() - 1);
            } else {
                selectIndex--;
            }
        } else {
            selectIndex = selectIndex;
        }
    }

    private void randomPlay() {
        selectIndex = (int) (Math.random() * (mGrindingEarsList.size() - 1));
    }

    @OnClick({R.id.iv_back, R.id.iv_before, R.id.iv_play, R.id.iv_next, R.id.ll_type, R.id.ll_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_before:
                if (null != mGrindingEarsList && mGrindingEarsList.size() > 0) {
                    caluateAfterIndex();
                    if (null != adapter) {
                        adapter.setSelectIndex(selectIndex);
                        lvSong.setSelection(selectIndex);
                        adapter.notifyDataSetInvalidated();
                    }
                    tvTitle.setText(mGrindingEarsList.get(selectIndex).getName());
                    showCicleImg();
                    startPlay();
                }
                break;
            case R.id.iv_play:
                if (null != mGrindingEarsList && mGrindingEarsList.size() > 0) {
                    if (null != mMusicService && isBind){
                        if (!mMusicService.player.isPlaying()) {
                            ivPlay.setImageResource(R.mipmap.pauseing);
                            mMusicService.goPlay();
                            reStartAnimation();
                        } else if (mMusicService.player.isPlaying()) {
                            mMusicService.pause();
                            ivPlay.setImageResource(R.mipmap.playing);
                            if (null != animationSmall) {
                                animationSmall.stop();
                            }
                        }
                    }else {
                       bindServiceConnection();
                    }
                }else {
                    ToastUtils.show(getApplicationContext(), "暂无歌曲", 100);
                }
                break;
            case R.id.iv_next:
                if (null != mGrindingEarsList && mGrindingEarsList.size() > 0) {
                    caluateNextIndex();
                    if (null != adapter) {
                        adapter.setSelectIndex(selectIndex);
                        lvSong.setSelection(selectIndex);
                        adapter.notifyDataSetInvalidated();
                    }
                    tvTitle.setText(mGrindingEarsList.get(selectIndex).getName());
                    showCicleImg();
                    startPlay();
                }
                break;
            case R.id.ll_type:
                //// 0是 顺序播放 1是随机播放 2是循环播放 3是单曲播放
                if (currentType == 0) {
                    currentType = 1;
                } else if (currentType == 1) {
                    currentType = 2;
                } else if (currentType == 2) {
                    currentType = 3;
                } else {
                    currentType = 0;
                }
                initPlayModeView(currentType);
                break;
            case R.id.ll_add://0代表首页过去的   1代表磨耳朵 过去的
                if (null != mGrindingEarsList && mGrindingEarsList.size() > 0) {
                    if (mMusicService.player.isPlaying()) {
                        mMusicService.pause();
                        ivPlay.setImageResource(R.mipmap.playing);
                    }
                }
                Intent mIntent = new Intent(GrindingEarsActivity.this, MoreReadingActivity.class);
                mIntent.putExtra("type", "1");
                startActivity(mIntent);
                break;
        }
    }

    private void reStartAnimation() {
        if (null != animationSmall) {
            if (!animationSmall.isShow()) {
                animationSmall.start();
            } else {
                animationSmall.stop();
                animationSmall = new RotateAnimation();
                animationSmall.with(ivBg);
                animationSmall.start();
            }
        } else {
            animationSmall.stop();
            animationSmall = new RotateAnimation();
            animationSmall.with(ivBg);
            animationSmall.start();
        }
    }

    //接受musicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if (message.getType() == 0) {//播放完成发过来的消息
            //
            //这里就要判断是列表循环还是其他的
            caluateNextIndex();
            if (null != mGrindingEarsList && mGrindingEarsList.size() > 0) {
                mSendStartOrFlowerNet = new SendStarOrFlowerNet(GrindingEarsActivity.this, null);
                mSendStartOrFlowerNet.initGetFlower(20
                        , mGrindingEarsList.get(selectIndex).getUserId(),
                        mGrindingEarsList.get(selectIndex).getBookId(),
                        "1", "4"
                );
                adapter.setSelectIndex(selectIndex);
                lvSong.setSelection(selectIndex);
                adapter.notifyDataSetInvalidated();
                tvTitle.setText(mGrindingEarsList.get(selectIndex).getName());
                showCicleImg();
                startPlay();
                ivPlay.setImageResource(R.mipmap.playing);
            }
        } else if (message.getType() == 1) {//播放失败发过来的消息
            MoreFunApplication.isOut = true;
            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }
            ivPlay.setImageResource(R.mipmap.playing);
            //弹出错误日志
            String error = "";
            try {
                int status = Integer.parseInt(message.getFileName());
                error = "音乐文件加载失败" + getErrorMessage(status, (int) (message.getTime()));
            }catch (Exception e){
                e.printStackTrace();
                error = "音乐文件加载失败" + message.getFileName();
            }
            ToastUtils.show(GrindingEarsActivity.this, error, 100);
        } else if (message.getType() == 2) {//获得音频时长
            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }
            ivPlay.setImageResource(R.mipmap.pauseing);
            duation = message.getNum();
            songDuration.setText(formatTime(message.getNum()));
        } else if (message.getType() == 1099) {
            initGetSongList();
            AppManager.getAppManager().finishActivity(MoreReadingActivity.class);
        } else {
            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }
            if (null != mMusicService && null != mMusicService.player && mMusicService.player.isPlaying()) {
                songDuration.setText(formatTime(mMusicService.player.getDuration()));
                songProgress.setText(formatTime(mMusicService.player.getCurrentPosition()));
                double currentPosition = mMusicService.player.getCurrentPosition();
                double duration = mMusicService.player.getDuration();
                seekbarMusic.setProgress((int) ((currentPosition / duration) * 100));
                ivPlay.setImageResource(R.mipmap.pauseing);
            }
        }
    }

    private String getErrorMessage(int what, int extra) {
        String message = "";
        switch (what) {
            case -1004:
                message = "MEDIA_ERROR_IO";
                break;
            case -1007:
                message = "MEDIA_ERROR_MALFORMED";
                break;
            case 200:
                message = "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK";
                break;
            case 100:
                message = "MEDIA_ERROR_SERVER_DIED";
                break;
            case -110:
                message = "MEDIA_ERROR_TIMED_OUT";
                break;
            case 1:
                message = "MEDIA_ERROR_UNKNOWN";
                break;
            case -1010:
                message = "MEDIA_ERROR_UNSUPPORTED";
                break;
        }
        switch (extra) {
            case 800:
                message = "MEDIA_INFO_BAD_INTERLEAVING";
                break;
            case 702:
                message = "MEDIA_INFO_BUFFERING_END";
                break;
            case 701:
                message = "MEDIA_INFO_METADATA_UPDATE";
                break;
            case 802:
                message = "MEDIA_INFO_METADATA_UPDATE";
                break;
            case 801:
                message = "MEDIA_INFO_NOT_SEEKABLE";
                break;
            case 1:
                message = "MEDIA_INFO_UNKNOWN";
                break;
            case 3:
                message = "MEDIA_INFO_VIDEO_RENDERING_START";
                break;
            case 700:
                message = "MEDIA_INFO_VIDEO_TRACK_LAGGING";
                break;
        }
        return message;
    }

    private String formatTime(long time) {
        return formatTime("mm:ss", time);
    }

    private String formatTime(String pattern, long milli) {
        int m = (int) (milli / android.text.format.DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / android.text.format.DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }

    private void startPlay() {
        try {
            ivPlay.setImageResource(R.mipmap.pauseing);
            if (null != mMusicService && isBind) {
                if (null != dialog && !dialog.isShow()) {
                    dialog.setMessage("加载歌曲中...");
                    dialog.show();
                }
                mMusicService.songNum = selectIndex;
                mMusicService.play();
                seekbarMusic.setProgress(0);
                songProgress.setText("00:00");
                reStartAnimation();
            }else {
                bindServiceConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (null != mMusicService && null != mMusicService.player) {
                mMusicService.stop();
            }
            unbindService(sc);
            isBind = false;
        }catch (Exception e){
            e.printStackTrace();
        }
        MoreFunApplication.isOut = true;//退出
        EventBus.getDefault().unregister(this);
        ivBg.clearAnimation();
        try {
            unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initPlayModeView(int playMode) {
        if (playMode == 0) {
            tvType.setText("顺序");
            ivType.setImageResource(R.mipmap.shunxu);
        } else if (playMode == 1) {
            tvType.setText("随机");
            ivType.setImageResource(R.mipmap.suiji);
        } else if (playMode == 2) {
            tvType.setText("循环");
            ivType.setImageResource(R.mipmap.mrd_loop_play);
        } else {
            tvType.setText("单曲");
            ivType.setImageResource(R.mipmap.danqu);
        }
    }
}
